#pragma once
#include <iostream>
#include <memory>
#include <stdlib.h>
#include "Socket.hpp"
#include "Connection.hpp"

class Listener
{
public:
    Listener(int port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }

    void Accepter(Connection *conn)
    {
        int sockfd = -1;
        while (1)
        {
            errno = 0;
            int code = 0;
            InetAddr addr;
            sockfd = _listensock->Accept(&addr, &code);
            if (sockfd > 0)
            {
                SetNonBlock(sockfd);
                uint32_t events = EPOLLIN | EPOLLET;
                conn->_R->AddConnection(sockfd, events, addr, NormalConnection);
            }
            else
            {
                if (code == EWOULDBLOCK)
                {
                    LOG(DEBUG, "底层数据传输完毕!\n");
                    break;
                }
                else if (code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "获取链接失败!\n");
                    break;
                }
            }
        }
    }

    int ListenSockfd()
    {
        return _listensock->Sockfd();
    }

    ~Listener()
    {
    }

private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};
